<template>
    <div class="white-box">
        <div>
            <el-button
                v-hasPermi="['enttp:waybill:loading']"
                class="table-mb"
                type="primary"
                @click="onClickEntrucking"
                >开始装车</el-button
            >
            <el-button
                v-hasPermi="['enttp:waybill:assignDriverDeparture']"
                class="table-mb"
                type="primary"
                @click="onClickAssign"
                >分配司机发车</el-button
            >
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">车次号：</span>
                <el-input
                    placeholder="请输入车次号"
                    v-model="state.tripsCode"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">订单/运单：</span>
                <el-input
                    placeholder="请输入订单/运单号"
                    v-model="state.code"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">车次状态：</span>
                <el-select
                    v-model="state.state"
                    placeholder="请选择车次状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.stateList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">车次车辆：</span>
                <SelectLoadMore
                    v-model:selectValue="state.carSid"
                    v-model:options="state.carOptions"
                    value="sid"
                    label="carNumber"
                    popperClass="car"
                    placeholder="请选择车辆"
                    :apiFun="getCarOptions"
                />
            </div>
            <div class="task-one__item">
                <span class="task-one__label">车次车辆：</span>
                <SelectLoadMore
                    v-model:selectValue="state.driverSid"
                    v-model:options="state.driverOptions"
                    value="sid"
                    label="nickName"
                    popperClass="driver"
                    placeholder="请选择司机"
                    :apiFun="getDriverOptions"
                />
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:trips:del']"
                @click="onClickDel()"
                >批量删除车次</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @sort-change="sortChange"
        >
            <el-table-column
                type="selection"
                width="55"
                v-hasPermi="['enttp:trips:del']"
                :selectable="(row) => row.wayBillState === 1"
            />
            <el-table-column
                prop="tripsCode"
                label="车次号"
                min-width="200"
                fixed="left"
            ></el-table-column>
            <el-table-column prop="state" label="车次状态" min-width="160">
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "enttp_waybill_trips_state",
                            row.state
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="carResult.carNumber"
                label="车牌号"
                min-width="120"
            ></el-table-column>
            <el-table-column
                prop="carResult.carHead"
                label="车辆负责人"
                min-width="120"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            ></el-table-column>
            <el-table-column
                label="司机"
                min-width="120"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            >
                <template #default="{ row }">
                    <p>
                        {{
                            row.userResult
                                ?.map((item) => item.nickName)
                                .join(",")
                        }}
                    </p>
                </template>
            </el-table-column>

            <!-- <el-table-column
                label="运单"
                min-width="270"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            >
                <template #default="{ row }">
                    {{
                        row.waybillResult
                            ?.map(
                                (item) =>
                                    `${
                                        item.wayBillCode
                                    }【${dictStore.getDictMemberName(
                                        "waybill_state",
                                        item.wayBillState
                                    )}】`
                            )
                            .join("，")
                    }}
                </template>
            </el-table-column> -->
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            />
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickDetail(row.sid),
                                    'v-hasPermi': ['enttp:trips:query'],
                                },
                                text: '详情',
                            },
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                    'v-hasPermi': ['enttp:trips:edit'],
                                },
                                text: '修改',
                                isRender: row.state === 1,
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:trips:del'],
                                },
                                text: '删除',
                                isRender: row.state === 1,
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-drawer v-model="state.showDetail" title="车次详情" size="600">
        <template v-if="detail">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">车次号</el-col>
                <el-col :span="18">{{ detail.tripsCode }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">车次状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "enttp_waybill_trips_state",
                        detail.state
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">备注</el-col>
                <el-col :span="18">{{ detail.note }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("data_status", detail.status)
                }}</el-col>
            </el-row>
            <!-- 车辆信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >车辆信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">车牌号</el-col>
                <el-col :span="18">{{ detail?.carResult.carNumber }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">车辆负责人</el-col>
                <el-col :span="18">{{ detail?.carResult.carHead }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">车辆状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "car_state",
                        detail?.carResult.carState
                    )
                }}</el-col>
            </el-row>
            <!-- 司机信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >司机信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">司机信息</el-col>
                <el-col :span="18">
                    <el-table
                        :data="detail.userResult"
                        row-key="sid"
                        :header-cell-style="{
                            background: '#F5F7FA',
                            textAlign: 'center',
                        }"
                        :cell-style="
                            ({ column }) => {
                                return {
                                    textAlign:
                                        column.className === 'operation-nav'
                                            ? 'left'
                                            : 'center',
                                    paddingLeft:
                                        column.className === 'operation-nav'
                                            ? '25px'
                                            : '0',
                                };
                            }
                        "
                        border
                        max-length="300"
                        element-loading-background="rgba(255, 255, 255, 0.6)"
                    >
                        <el-table-column
                            prop="nickName"
                            label="昵称"
                            min-width="120"
                            fixed="left"
                        ></el-table-column>
                        <el-table-column
                            prop="phone"
                            label="手机号"
                            min-width="120"
                        ></el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <!-- 运单信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >运单信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">运单信息</el-col>
                <el-col :span="18">
                    <el-table
                        :data="detail.waybillResult"
                        row-key="sid"
                        :header-cell-style="{
                            background: '#F5F7FA',
                            textAlign: 'center',
                        }"
                        :cell-style="
                            ({ column }) => {
                                return {
                                    textAlign:
                                        column.className === 'operation-nav'
                                            ? 'left'
                                            : 'center',
                                    paddingLeft:
                                        column.className === 'operation-nav'
                                            ? '25px'
                                            : '0',
                                };
                            }
                        "
                        border
                        max-length="300"
                        element-loading-background="rgba(255, 255, 255, 0.6)"
                    >
                        <el-table-column
                            prop="orderCode"
                            label="订单号"
                            min-width="200"
                            fixed="left"
                        ></el-table-column>
                        <el-table-column
                            prop="wayBillCode"
                            label="运单号"
                            min-width="200"
                        ></el-table-column>
                        <!-- <el-table-column label="运单状态" min-width="160">
                            <template #default="{ row }">
                                {{
                                    dictStore.getDictMemberName(
                                        "waybill_state",
                                        row.wayBillState
                                    )
                                }}
                            </template>
                        </el-table-column> -->
                    </el-table>
                </el-col>
            </el-row>
        </template>
    </el-drawer>

    <el-dialog
        v-model="state.showAssign"
        title="分配司机发车"
        width="350"
        destroy-on-close
    >
        <DriverDeparture @success="successDriverDeparture" />
    </el-dialog>
</template>

<script setup>
import { inject, reactive, onMounted, onActivated, toRefs } from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import SelectLoadMore from "@/components/selectLoadMore.vue";
import { getWaybillDrivers } from "@/apis/order/waybill";
import { getCars } from "@/apis/enterprise/car.js";
import { getTrips, delTrips, getTripDetail } from "@/apis/order/trip.js";
import { useDictStore } from "@stores/dict.js";
import DriverDeparture from "./DriverDeparture.vue";

const dictStore = useDictStore();
dictStore
    .getDictMembers("enttp_waybill_trips_state")
    .then((res) => (state.stateList = res));
dictStore.getDictMembers("waybill_state");
dictStore.getDictMembers("car_state");

const router = useRouter();
const $message = inject("$message");

const state = reactive({
    stateList: [],
    lineOptions: [], // 线路列表
    carOptions: [], // 车辆列表
    orderOptions: [], // 订单列表
    driverOptions: [], // 司机列表
    ascended: false,
    sortFieldName: null,
    carSid: null,
    code: null,
    driverSid: null,
    state: null,
    tripsCode: null,
    sidList: [],
    showAssign: false, // 发车
    showDetail: false, // 详情
    detail: null,
});

const { detail } = toRefs(state);

onActivated(() => {
    pubParams(getList);
});

const getCarOptions = async (params) => {
    const res = await getCars({
        ...params,
        carNumber: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getDriverOptions = async (params) => {
    const res = await getWaybillDrivers({
        ...params,
        nickName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getTrips({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            carSid: state.carSid,
            code: state.code,
            driverSid: state.driverSid,
            state: state.state,
            tripsCode: state.tripsCode,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除车次信息吗？");
    const res = await delTrips({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const onClickDetail = (sid) => {
    state.showDetail = true;
    state.detail = null;
    getDetails(sid);
};

const getDetails = async (sid) => {
    const res = await getTripDetail({ sid });
    if (res.data.code == 200) {
        state.detail = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const onClickEntrucking = () => {
    router.push({ name: "EntruckingAdd" });
};

const onClickEdit = (sid) => {
    sid && router.push({ name: "EntruckingEdit", query: { sid } });
};

// 显示分配司机发车弹窗
const onClickAssign = () => {
    state.showAssign = true;
};

// 发车成功
const successDriverDeparture = () => {
    state.showAssign = false;
    pubParams(getList);
};
</script>

<style lang="less" scoped></style>
